import { TOKEN, USER_INFO } from '@/const/storage'
import { isObject, isArray } from '@/utils/type'

// 统一
export function setStorage(key, value, type = 'localStorage') {
  if (!key) return
  if (isObject(value) || isArray(value)) {
    value = JSON.stringify(value)
  }

  window[type].setItem(key, value)
}

export function getStorage(key, type = 'localStorage', initValue = null) {
  if (!key) return
  let data = window[type].getItem(key)
  try {
    return JSON.parse(data)
  } catch (error) {
    return data || initValue
  }
}

export function removeItem(key, type = 'localStorage') {
  if (!key) return
  window[type].removeItem(key)
}

// token
export const setToken = (value) => setStorage(TOKEN, value)
export const getToken = () => getStorage(TOKEN)
export const removeToken = () => removeItem(TOKEN)

// userInfo
export function setUser(value) {
  if (!isObject(value))
    throw new Error(`userInfo must be object, not of ${typeof value}`)
  setStorage(USER_INFO, value)
}

export function getUser() {
  const user = getStorage(USER_INFO)
  if (!user) return null

  return user
}

export const removeUser = () => removeItem(USER_INFO)
